<template>
  <div class="container">
    <div class="container__header">
      <Header :currentId="4" />
    </div>
    <div class="container__content">
      <div class="container__content__opration">
        <div class="justify-start">
          <date-tab @selectDate="handleSelectDate" ref="reset"></date-tab>
          <div class="select-type">
            <span>区域</span>
            <el-select @change="selectChanged" v-model="serviceType" placeholder="请选择" size="medium" style="background-color: transparent">
              <el-option label="全部" value="0">
              </el-option>
              <el-option v-for="item in serviceList" :key="item.id" :label="item.zoneName" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="opration-btn">
          <span class="opration-btn__export" @click="exportData()">导出</span>
          <span class="opration-btn__reserve" @click="reserveType()">重置</span>
          <span class="opration-btn__search" @click="searchList()">开始检索</span>
        </div>
      </div>

      <div class="container__content__list">
        <div class="container__content__list__title">
          <div class="front align-center">
            <img src="@/assets/biaoti@2x.png" />
            <span class="font18">人员时长情况</span>
            <span>单位：分</span>
          </div>
          <div class="my-sort">
            <span :class="{ active: sort == 1 }" @click="getSort(1)">降序</span>
            <span :class="{ active: sort == 0 }" @click="getSort(0)">升序</span>
          </div>
        </div>
        <el-scrollbar style="width: 100%">
          <div class="justify-between container__content__list__box">
            <div class="container__content__list__box__item" v-for="item in countArr" :key="item.id">
              <el-image style="width: 168px; height: 168px; margin: 24px 24px 8px 24px" :preview-src-list="countArr.map(_item=>_item.path)" :src="item.path" fit="scale-down" :lazy="true"></el-image>
              <div class="data-item">
               <div><span>{{ item.userName? item.userName : '未识别' }}</span></div>
               <div><span>{{ Math.ceil(item.duration < 1 ? 1 : item.duration) }}</span><span class="frequency">分钟</span></div>
              </div>
              <div class="time"><span>时间：{{ item.daytime }}</span></div>
            </div>
          </div>
        </el-scrollbar>
        <div class="container__content__list__pagination justify-end">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNo" :page-sizes="pageSizeArr" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
          </el-pagination>
        </div>
      </div>
    </div>

    <div class="container__chart justify-between">
      <div class="container__chart__left">
        <div class="front align-center">
          <img src="@/assets/biaoti@2x.png" />
          <span class="font18">统计结果分析</span>
        </div>
        <div class="echart-box">
          <bar-echart :echartObj="echartObj"></bar-echart>
        </div>
      </div>
      <div class="container__chart__right">
        <div class="front align-center">
          <img src="@/assets/biaoti@2x.png" />
          <span class="font18">按时间段维度分析</span>
        </div>

        <div class="echart-box">
          <pie-echart :optionData="optionData" :startTime="startTime" :endTime="endTime" @showTimeFrequency="showTimeFrequency"></pie-echart>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import DateTab from "@/components/DateTab.vue";
import BarEchart from "@/components/BarEchart.vue";
import PieEchart from "@/components/PieEchart.vue";
import { mapGetters } from "vuex";

import {
  getDurationCountList,
  getServiceList,
  getDurationBar,
  getDurationPie,
  timeDataExport
} from "@/api/home";
import {timestampToDate} from "@/utils/dateUtils";


export default {
  name: "mostOnce",
  components: {
    Header,
    DateTab,
    BarEchart,
    PieEchart,
  },
  computed: { ...mapGetters(["userId"]) },
  data() {
    return {
      searchUserId: 0,
      pageNo: 1,
      pageSize: 20,
      pageSizeArr: [10, 20, 30, 40, 50, 60],
      totalCount: 0,
      countArr: [],
      dayType: 30,
      startTime: null,
      endTime: null,

      sort: 1, //排序
      serviceType: "0", //服务类型
      serviceList: [], //服务列表

      echartObj: {}, //柱状图数据
      optionData: {} //饼图数据
    };
  },

  mounted() {
    //this.getDurationCountList();
    this.getServiceList();
    //this.getCountBar();
    //this.getCountPies();
  },

  methods: {
    selectChanged(){
      this.searchList();
    },
    //服务检索类型
    async getServiceList() {
      let res = await getServiceList();
      if (res.code == 200) {
        this.serviceList = res.data;
      }
    },
    async getDurationCountList() {
      let res = await getDurationCountList({
        orderType: this.sort,
        zoneId: this.serviceType,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        dayType: this.dayType,
        startTime: this.startTime,
        endTime: this.endTime,
        userId: this.searchUserId
      });
      if (res.code == 200) {
        this.countArr = Array.from(
          new Set([...res.data.lists, ...this.countArr])
        );
        this.totalCount = res.data.count;
      }
    },
    //日期选择器返回的时间
    handleSelectDate(e) {
      console.log(e);
      this.startTime = new Date(`${e.date[0]} 00:00:00`).getTime() / 1000;
      this.endTime = new Date(`${e.date[1]} 23:59:59`).getTime() / 1000;
      this.dayType = e.dateType;

      console.log(this.startTime, this.endTime, this.dayType)

      this.searchList();
    },
    handleUser(userId) {
      this.searchUserId = userId;
      this.searchList();
    },

    async exportData() {
      let query = {
        startTime: this.startTime,
        endTime: this.endTime,
        zoneId:this.serviceType
      };
      console.log("query参数",query)
      let res = await timeDataExport(query);
      if (res) {
        const startTimeDate = timestampToDate(this.startTime);
        const endTimeDate = timestampToDate(this.endTime);
        let data = "人员时长情况" + startTimeDate + "至" + endTimeDate + "data.xlsx"
        const blob = new Blob([res], {
          type:
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"
        });
        try {
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, data);
          } else {
            let downloadElement = document.createElement('a');
            let href = window.URL.createObjectURL(blob); // 创建下载的链接
            downloadElement.href = href;
            downloadElement.download = data; // 下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); // 点击下载
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
          }
          this.$message.success("导出成功");

        }catch (e) {
          this.$message.error("导出失败");
        }
      }
    },
    reserveType() {
      this.serviceType = "";
      this.sort = 1;
      this.searchUserId = "";
      this.searchList();
      this.$refs.reset.reset()
    },

    searchList() {
      this.pageNo = 1;
      this.countArr = [];
      this.getDurationCountList();
      this.getCountBar();
      this.getCountPies();
    },

    //柱状图
    async getCountBar() {
      let res = await getDurationBar({
        startTime: this.startTime,
        endTime: this.endTime,
        dayType: this.dayType,
        userID: this.searchUserId
      });
      // console.log(res);
      if (res.code == 200) {
        this.echartObj = {
          data: res.data.legend,
          xAxis: res.data.xdata,
          series: res.data.series, //[],
          // color: carArr.slice(0, res.data.legend.length),
          unit: "人次"
        };
      }
    },

    async getCountPies() {
      let res = await getDurationPie({
        startTime: this.startTime,
        endTime: this.endTime,
        dayType: this.dayType,
        userId: this.searchUserId
      });
      // console.log(res);
      if (res.code == 200) {
        //console.log("返回数据",res.data)
        var data = [];

        if (res.data.series.length > 0) {
            data = res.data.series.filter(index => {
            return index.value !== 0;
          })
        }
        this.optionData = {
          data: data,
          top: 100,
          right: 40,
          gap: 15,
          title:'总人次'
        };
      }
    },

    handleCurrentChange(e) {
      this.pageNo = e;
      this.countArr = [];
      this.getDurationCountList();
    },
    handleSizeChange(e) {
      this.pageSize = e;
      this.pageNo = 1;
      this.countArr = [];
      this.getDurationCountList();
    },

    getSort(index) {
      if (this.sort === index) {
        return;
      }
      this.sort = index;
      this.searchList();
    },

    // 展示页面
    showTimeFrequency(data) {
      this.$router.push( {name: "timeFrequency",params:data})
    }
  }
};
</script>


<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  .front {
    .font18 {
      color: #fff;
      font-size: 18px;
      padding-right: 16px;
    }

    img {
      width: 24px;
      height: 24px;
      margin-right: 8px;
    }
  }
  &__content {
    width: 1888px;
    height: auto;
    border-radius: 8px;
    margin: 16px auto;
    box-sizing: border-box;

    &__opration {
      padding: 0 24px;
      width: 100%;
      height: 84px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #303136;

      .select-type {
        span {
          padding: 0 24px;
          color: #949ba4;
          font-size: 14px;
        }
      }

      .opration-btn {
        span {
          display: inline-block;
          width: 88px;
          height: 36px;
          line-height: 36px;
          border-radius: 4px;
          cursor: pointer;
        }

        &__export {
          border: 1px solid #5cfbff;
          color: #5cfbff;
          margin-right: 24px;
        }

        &__reserve {
          border: 1px solid #5cfbff;
          color: #5cfbff;
          margin-right: 24px;
        }

        &__search {
          background-color: #5cfbff;
          color: #17181a;
        }
      }
    }

    &__list {
      margin-top: 16px;
      background: #303136;
      padding-bottom: 24px;

      &__title {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #949ba4;
        padding: 28px 24px 0 24px;
      }
      &__box {
        width: 100%;
        height: auto;
        margin-top: 16px;
        padding: 0 24px;
        display: flex;
        &__item {
          width: 216px;
          height: 252px;
          background: #363940;
          border-radius: 4px;
          border: 1px solid #45777a;
          margin-top: 16px;
          margin-right: 16px;

          img {
            width: 168px;
            height: 168px;
          }

          span {
            color: #fff;
          }
        }
      }

      &__pagination {
        width: 100%;
        margin-top: 24px;
        padding: 0 24px;
        box-sizing: border-box;
      }
    }
  }

  &__chart {
    width: 1888px;
    margin: 16px auto;
    &__left,
    &__right {
      width: 936px;
      height: 480px;
      background-color: #303136;
      border-radius: 8px;

      .front {
        width: 100%;
        box-sizing: border-box;
        padding: 28px 0 27px 24px;
      }

      .echart-box {
        width: 100%;
        height: 400px;

      }
    }
    &__right {
      margin-left: 16px;
    }
  }
  .data-item{
    display: flex;
    margin: 0 25px;
    justify-content: space-between;
    font-size: 16px;
    .frequency{
      font-size: 14px;
      color: #949BA4;
    }
  }
  .time{
    display: flex;
    margin-left: 25px;
    span{
      font-size: 14px;
      color: #949BA4;
    }
  }
}
</style>
